#include "gpio.h"

Gpio::Gpio()
{
    qtimer = new QTimer();
    qtimer->setInterval(50);
    qtimer->start();
    readgpio();
    connect(qtimer,SIGNAL(timeout()),this,SLOT(timerOutSlot()));    //当定时结束后，调用一次读gpio
}

Gpio::~Gpio()
{
    qtimer->stop();
    delete qtimer;
}

int Gpio::readgpio()    //上拉电阻，当接通后为低电平
{
    int fd = -1;
    int dir = -1;
    char buf[1];

    fd = open(GPIO_EXP0_INT_VAL, O_RDWR);
    dir = open(GPIO_EXP0_INT_DIR, O_RDWR);
    if(fd < 0)
    {
        printf("Failed to open GPIO value in %s.\n",
                GPIO_EXP0_INT_VAL);
        return -1;
    }
    if(dir < 0)
    {
        printf("Fail to open GPIO direction in %s.\n",
                GPIO_EXP0_INT_DIR);
    }

    read(fd, buf, 1);

    if(buf[0] == '0')   //如果检测到低电平，则将其置高，若下次读还是低，则说明接通。
    {
        write(dir, "out", 3);
        write(fd, "1", 1);
        write(dir, "in", 2);
        close(fd);
        close(dir);
        return 0;
    }
    else
    {
        close(fd);
        close(dir);
        return 1;
    }
}

int Gpio::changeSignal()
{
    last_level = this_level;
    this_level = readgpio();
    if (this_level ==0 && last_level == 1)
        return 1;
    else if (this_level ==0 && last_level == 0)
        return 1;
    else
        return 0;
}

void Gpio::timerOutSlot()
{
    if(changeSignal()==1 && pylonflag == 0)
    {
        printf("shot!\n");
        qtimer->stop();
        pylonflag = 1;
        emit shotSignal();
    }
    else if(changeSignal()==1 && pylonflag == 1)
    {
        printf("stop!\n");
        qtimer->stop();
        pylonflag = 0;
        pylonstopflag = 1;
    }
}

void Gpio::timerStartSlot()
{
    qtimer->setInterval(50);
    qtimer->start();
    readgpio();
    connect(qtimer,SIGNAL(timeout()),this,SLOT(timerOutSlot()));    //当定时结束后，调用一次读gpio
}
